package com.googlecode.c4e.ui.actions;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionDelegate;

import com.googlecode.c4e.api.model.Project;
import com.googlecode.c4e.ui.ContinuumPlugin;
import com.googlecode.c4e.ui.actions.internal.BuildLogRunnable;

public class OpenBuildLogAction extends ActionDelegate {

	private Project project;

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection != null && selection instanceof IStructuredSelection) {
			IStructuredSelection isel = (IStructuredSelection) selection;
			if (isel.getFirstElement() instanceof Project) {
				this.project = (Project) isel.getFirstElement();
			}
		}
	}

	@Override
	public void run(IAction action) {
		if (project != null) {
			try {
				IWorkbench workbench = PlatformUI.getWorkbench();
				IEditorRegistry registry = workbench.getEditorRegistry();
				IWorkbenchPage page = workbench.getActiveWorkbenchWindow()
						.getActivePage();
				IEditorDescriptor descriptor = registry
						.getDefaultEditor("build.log");
				String editorId;
				if (descriptor == null) {
					editorId = "org.eclipse.ui.DefaultTextEditor";
				} else {
					editorId = descriptor.getId();
				}
				IRunnableWithProgress runnable = new BuildLogRunnable(project,
						page, editorId);
				ProgressMonitorDialog dialog = new ProgressMonitorDialog(
						PlatformUI.getWorkbench().getActiveWorkbenchWindow()
								.getShell());
				dialog.run(true, true, runnable);
			} catch (Exception e) {
				ContinuumPlugin.getDefault().log("openInBrowser", e);
				throw new RuntimeException(e.getMessage(), e);
			}
		}
	}
}
